package com.abxh.jetpack.room.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.EditText
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.abxh.jetpack.base.BaseViewModelActivity
import com.abxh.jetpack.room.R
import com.abxh.jetpack.room.api.AppDatabase
import com.abxh.jetpack.room.api.OnItemClickListener
import com.abxh.jetpack.room.bean.User
import com.abxh.jetpack.room.viewmodel.ViewModelRoom
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * Created by dab on 2021/8/31 11:45
 */
open class RoomTestActivity : BaseViewModelActivity<ViewModelRoom>() {
    val roomAdapter = RoomAdapter()

    @SuppressLint("MissingSuperCall")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.room_activity_test)
        findViewById<RecyclerView>(R.id.rv_content).apply {
            adapter = roomAdapter
            layoutManager = LinearLayoutManager(this@RoomTestActivity)
        }
        viewModel.viewModelScope.launch {
            AppDatabase.getDatabase(this@RoomTestActivity).mUserDao()?.getAll()?.collect {
                roomAdapter.setData(it)
            }
        }
        roomAdapter.setOnItemClickListener(OnItemClickListener { view, position, t ->
            viewModel.viewModelScope.launch {
                AppDatabase.getDatabase(this@RoomTestActivity).mUserDao()?.delete(t)
            }
        })
    }

    fun add(view: View) {
        val name = findViewById<EditText>(R.id.et_name).text
        val age = findViewById<EditText>(R.id.et_age).text
        if (name.isNullOrEmpty() && age.isNullOrEmpty()) {
            return
        }
        viewModel.viewModelScope.launch {
            AppDatabase.getDatabase(this@RoomTestActivity).mUserDao()?.insertAll(User().apply {
                this.age=age.toString().toInt()
                this.name=name.toString()
            })
        }

    }
}